import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import MainLayout from '../layout/MainLayout.vue'
import AlertManagement from '../views/AlertManagement.vue'
import ClientStatus from '../views/ClientStatus.vue'
import Dashboard from '../views/Dashboard.vue'
import NotFound from '../views/NotFound.vue'
import Login from '../views/Login.vue'

const routes = [
  // 公开路由
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: {
      public: true // 不需要登录
    }
  },

  // 需要认证的路由
  {
    path: '/',
    component: MainLayout,
    meta: {
      requiresAuth: true // 需要登录
    },
    children: [
      { path: '', name: 'dashboard', component: Dashboard },
      { path: 'alerts', name: 'alert-management', component: AlertManagement },
      { path: 'clients', name: 'client-status', component: ClientStatus }
    ]
  },

  // 404 路由
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: NotFound,
    meta: {
      public: true // 不需要登录
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()

  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    // 检查是否已经认证
    if (authStore.isAuthenticated) {
      // 已经认证，直接进入
      next()
    } else {
      // 未认证，检查token是否有效
      const tokenValid = await authStore.validateToken()
      if (tokenValid) {
        next()
      } else {
        // token无效，跳转到登录页
        next({ name: 'login', query: { redirect: to.fullPath } })
      }
    }
  } else {
    // 公开路由
    if (to.name === 'login' && authStore.isAuthenticated) {
      // 已经登录，访问登录页时跳转到首页
      next('/')
    } else {
      next()
    }
  }
})

export default router
